---
--类名: Desktop.lua
--创建日期: 2015-3-31
--创建人: 陈小虎
--功能描述: 世界桌面视图
--修改内容:
--修改日期:
--修改人:
--修改备注:
--

local DungeonInfo = import(".DungeonInfo")
local DungeonSecretInfo = import(".DungeonSecretInfo")
local PlayerInfo = import(".PlayerInfo")
local TeamGroup = import(".TeamGroup")
local MiniMap = import(".MiniMap")
local Wheel = import(".Wheel")
local FourthTips = import(".FourthTips")
local MapBuffView = import(".MapBuffView")
local MsdkCommunityRender = import(".MsdkCommunityRender")
local Advert = import(".Advert")
local Director = cc.Director:getInstance()

local NodeGetChildByName = cc.Node.getChildByName
local NodeSetVisibleFunc = cc.Node.setVisible

local Desktop = class("Desktop",function()
    return display.newLayer()
end)

function Desktop:ctor(model)
    cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()

    self._model = model

    self:setTouchSwallowEnabled(false)

    --ui根节点
    local node,bindingNodes = cc.uiloader:load(Res.MainDesktopScene, true, false)
    self:addChild(node,1)
    display.doLayout(node)

    self.mUINode = node

    display.setCascadeColorEnabled(node,true)
    display.setCascadeOpacityEnabled(node,true)

    self._funcBtns = nil

    self:initNodes()

    self:initBottomTimeline()
    self:openBottomAction()

    self:showDebugInfo()

    self:enableNodeEvents()
end

function Desktop:showDebugInfo()
    if DEBUG > 0 then
        --x坐标
        self.labelX = display.newTTFLabel({
             text = "default",
             --font = "Arial",
             size = 20,
        })
        self.labelX:setAnchorPoint(cc.p(0.5,0.5))
        self.labelX:setPosition(cc.p(display.width / 2,display.height - 210))
        self:addChild(self.labelX)


        --y坐标
        self.labelY = display.newTTFLabel({
            text = "default",
--            font = "Arial",
            size = 20,
        })
        self.labelY:setAnchorPoint(cc.p(0.5,0.5))
        self.labelY:setPosition(cc.p(display.width / 2,display.height - 230))
        self:addChild(self.labelY)

        self.labelMapId = display.newTTFLabel({
             text = "default",
--             font = "Arial",
             size = 20,
        })
        self.labelMapId:setAnchorPoint(cc.p(0.5,0.5))
        self.labelMapId:setPosition(cc.p(display.width / 2,display.height - 250))
        self:addChild(self.labelMapId)

        self.labelUid = display.newTTFLabel({
             text = "default",
--             font = "Arial",
             size = 20,
        })
        self.labelUid:setAnchorPoint(cc.p(0.5,0.5))
        self.labelUid:setPosition(cc.p(display.width / 2,display.height - 270))
        self:addChild(self.labelUid)
        
        --server x坐标
        self.labelServerX = display.newTTFLabel({
             text = "default",
             --font = "Arial",
             size = 20,
        })
        self.labelServerX:setAnchorPoint(cc.p(0.5,0.5))
        self.labelServerX:setPosition(cc.p(display.width / 2,display.height - 190))
        self:addChild(self.labelServerX)

        local listener = cc.EventListenerCustom:create("temp_pos_desktop_refresh",function(event)
            self.labelServerX:setString("serverx:" .. (FieldManager:getSelfEntity():getX() or 0))
            self.labelX:setString("px:" .. math.floor(FieldManager:getCharacterX() or 0))
            self.labelY:setString("py:" .. math.floor(FieldManager:getCharacterY() or 0))
            self.labelMapId:setString("mapId:" .. MapManager:getMapId())
            self.labelUid:setString("uid:" .. (UD:getUid() or "default"))
        end)
        Director:getEventDispatcher():addEventListenerWithSceneGraphPriority(listener,self)
    end
    if DEVELOP_MODEL then
        -- local btn = ccui.Button:create(Res.commonUIPath.."common_btn_s2_n.png", Res.commonUIPath .."common_btn_s2_p.png", "", 1)
        -- local label = display.newTTFLabel({text = "开发测试", size = 24, color = display.COLOR_BLACK})
        -- local size = btn:getContentSize()
        -- label:setPosition(size.width / 2, size.height / 2)
        -- btn:addChild(label)
        -- btn:setPosition(80, display.ui_height/2 - 30)
        -- self:addChild(btn)
        -- btn:addClickEventListener(function()
            require("test.TestManage"):init()
            require("Language")
        -- end)
    end
end

function Desktop:onEnter()
    self.playerHandler = UD.player:onChanged(function(name,old,new)
        if name=="level" or name == "name" then
            self._playerInfo:refreshNameLevel()
        end
    end)
    self._walletHandler = UD:onChanged("wallet",function(name,old,new)
        if name == "power" then
            self._playerInfo:refreshPower()
        elseif name == "talentPoint" then
            UD.redPoint:checkStateByKey(RedPointConstant.Skill_Talent)
        elseif name == "skillPoint" then
            UD.redPoint:checkStateByKey(RedPointConstant.Skill_Skill)
        end
    end)

    self.badgeHandler = UD.badge:onChanged(function(id,num)
        self:_refreshFuncRedPoint(id, num)
    end)

    self.redPointHandler = UD.redPoint:onChanged(function(keyMap)
        self:_refreshFuncRedPointByRedPointData(keyMap)
    end)

    local ret = {}
    ret[#ret+1] = EM:on("onNormalCountDown",function(name,params)
        self:showNormalCountDown(params)
    end)
    ret[#ret+1] = EM:on("onDungeonCountDown",function(name,params)
        self:showDungeonCountDown(params.second)
    end)
    ret[#ret+1] = EM:on("onDungeonUi",function(name,params)
        if params.status == "open" then
            if params.type == "secret" then
                self.m_rightNode:setVisible(false)
                self._secretInfo:showDungeonUi()
            else
                self:showDungeonUi()
            end
        elseif params.status == "close" then
            if params.type == "secret" then
                self.m_rightNode:setVisible(true)
                self._secretInfo:hideDungeonUi()
            else
                self:hideDungeonUi()
            end
            self:hideDungeonCountDown()
        end
    end)
    ret[#ret+1] = EM:on("onDungeonFinished",function(name,params)
        self._dungeonInfo:setDungeonUiFinished(true)
    end)

    ret[#ret+1] = EM:on("onMapChanged",function()
        local mapId = MapManager:getMapId()
        self._miniMap:setData(mapId)
        -- 隐藏倒计时
        self:hideNormalCountDown()

        self._wheel:resetStatus()
    end)
    ret[#ret+1] = EM:on("onBottomNodeChanged",function(name,params)
        if params.status == "show" then
            self:showBottomNodes()
        elseif params.status == "hide" then
            self:hideBottomNodes()
        end
    end)
    ret[#ret+1] = EM:on("onSkillChangeNodeChanged", function(name, params)
        if params.status == "show" then
            self:isShowSkillChangeNode(true)
        elseif params.status == "hide" then
            self:isShowSkillChangeNode(false)
        end
    end)
    ret[#ret+1] = EM:on(ViewEvent.CSGuildWar_DeskTopStateChangge, function(name, status)
        if status == 1 then
            self:hideCSGuildWarDesktop()
        elseif status == 2 then
            self:hideCSGuildWarDesktopState2()
        end
    end)

    -- 添加跨服工会战  比分面板
    -- 移除逻辑 CrossServerController closeGuildWarBattleScorePanel
    ret[#ret+1] = EM:on(ViewEvent.CSGuildWar_ShowGuildWarScorePanelToDesktop, function(name)
        if not self._csGuildWarScorePanel then
            local GuildWarBattleScorePanel = require("app.crossServer.views.guildWar.panels.GuildWarBattleScorePanel")
            local csGuildWarScorePanel = GuildWarBattleScorePanel.create()
            csGuildWarScorePanel:setPosition( cc.p( display.width/2 , display.height* 0.75 - 50 ))
            self._csGuildWarScorePanel = csGuildWarScorePanel
            self:addChild(csGuildWarScorePanel)
        end
    end)

    ret[#ret+1] = EM:on(ViewEvent.CSGuildWar_CloseGuildWarScorePanelToDesktop, function(name)
        if self._csGuildWarScorePanel and not cc.isDead(self._csGuildWarScorePanel) then
            self._csGuildWarScorePanel:removeFromParent()
            self._csGuildWarScorePanel = nil
        end
    end)

    self._emHandles = ret
end

function Desktop:onExit()
    UD.badge:unChanged(self.badgeHandler)
    UD.player:unChanged(self.playerHandler)
    UD.redPoint:unChanged(self.redPointHandler)
    
    UD:unChanged("wallet", self._walletHandler)
    UD:unChanged("mapBuff",self.mapBuffHandler)
    MiniMap:remove()
    if self._wheel then
        self._wheel:disposeScheduler()
    end

    if self._emHandles then
        for i,v in ipairs(self._emHandles) do
            EM:remove(v)
        end
    end
    EM:remove(self.redpointHandler)
end

function Desktop:getUiNode()
    return self.mUINode
end

function Desktop:getTopScene()
    return self.m_topNode
end

function Desktop:initData()
    self._playerInfo:refreshPlayerInfo()

    self._teamGroup:refreshTeamGroup()

    self._mapBuffView:startRefresh()
end

function Desktop:initNodes()
    self.m_bottomNode = self.mUINode:getChildByName("function")
    self.m_bottomMoreBtn = self.m_bottomNode:findChild("Panel/btn_more")
    self.m_bottomBtnPanel = self.m_bottomNode:findChild("Panel/Panel_btn")
    self.m_bottomOtherPanel = self.m_bottomNode:findChild("Panel/Panel_other")

    self.m_rightNode = self.mUINode:getChildByName("Panel_game")
    self.m_topNode = self.mUINode:getChildByName("Panel_operate")
    self.m_bossNode = self.mUINode:getChildByName("boss")

    self._taskRoot = self.mUINode:getChildByName("task")

    self._playerRoot = self.mUINode:getChildByName("head")
    self._playerInfo = PlayerInfo.new(self._playerRoot)
    self:initHeadRedPoint()

    local teamGroupRoot = self._playerRoot:findChild("Panel/Panel_head")
    local teamFunctionRoot = self._playerRoot:findChild("Panel/Panel_team")
    teamGroupRoot:setVisible(true)
    teamFunctionRoot:setVisible(true)
    self._teamGroup = TeamGroup.new(teamGroupRoot,teamFunctionRoot)

    -- dungeon info
    self._dungeonInfo = DungeonInfo.new(self.m_bossNode)

    -- secret info
    self._secretInfo = DungeonSecretInfo.new()
    local secretNode = self._secretInfo.secretNode
    self.mUINode:addChild(secretNode)
    secretNode:setPosition(self.m_bossNode:getPosition())
    secretNode:hide()
    -- self._secretInfo:showDungeonUi()

    -- 移动滚轮／按钮
    local wheelRoot = self.mUINode:findChild("Panel_rocker")
    self._wheel = Wheel.new(wheelRoot)

    -- 右上角小地图
    local mapNode = self.mUINode:getChildByName("map")
    self._miniMap = MiniMap.create(mapNode)

    --地图Buff
    local buffNode = self.mUINode:getChildByName("Panel_buff_world")
    self._mapBuffView = MapBuffView.create(buffNode)

    -- 右下角提示节点
    local fourthTips = self.mUINode:getChildByName("fourthTips")
    self._fourthTips = FourthTips.create(fourthTips)

    -- 地下城竞速模式下技能切换按钮
    self.m_skillChangeNode = self.mUINode:getChildByName("Panel_js_skill")
    self.m_skillChangeNode:setVisible(false)
    self.m_skillChangeNode:findChild("01Button"):addClickEventListener(function()
        self:dispatchEvent({name = "onOpenFunction",functionId = Constant.FUNC_TYPE_SKILL_CHANGE})
    end)


    -- 初始化功能按钮
    self:_initFuncBtns()

    -- top btns show/hide switch
    self:_initTopSwtich()
end

function Desktop:initHeadRedPoint()
    local h = self._playerRoot:findChild("Panel/head")
    local r = h:findChild("Panel/tishi")
    local rednode = display.addNewPoint(r)

    r:setVisible(app:sendMsg("CaptainModelRedPoint", "captainRoomHasRedPoint"))
    self.redpointHandler =EM:on(app:getInst("CaptainModelRedPoint").RedPointChange, function()
        r:setVisible(app:sendMsg("CaptainModelRedPoint", "captainRoomHasRedPoint"))
    end)
end

function Desktop:hideBottomNodes()
    if not self.m_bottomNode then return end
    self.m_bottomNode:setVisible(false)
    self._topSwitch:setVisible(false)
    self.m_topNode:setVisible(false)
    self._taskRoot:setVisible(false)

    local teamGroupRoot = self._playerRoot:findChild("Panel/Panel_head")
    local teamFunctionRoot = self._playerRoot:findChild("Panel/Panel_team")
    teamGroupRoot:setVisible(false)
    teamFunctionRoot:setVisible(false)
end

function Desktop:showBottomNodes()
    if not self.m_bottomNode then return end
    self.m_bottomNode:setVisible(true)
    self._topSwitch:setVisible(self._topSwitchVisible)
    self.m_topNode:setVisible(true)
    self._taskRoot:setVisible(true)

    local teamGroupRoot = self._playerRoot:findChild("Panel/Panel_head")
    local teamFunctionRoot = self._playerRoot:findChild("Panel/Panel_team")
    teamGroupRoot:setVisible(true)
    teamFunctionRoot:setVisible(true)
end

function Desktop:getTrackRoot()
    return self._taskRoot
end

function Desktop:decideFunctionOpen()
    self._miniMap:setVisible(UIHandler:isFunctionOpen(Constant.FUNC_TYPE_MINIMAP))
    self._playerRoot:setVisible(UIHandler:isFunctionOpen(Constant.FUNC_TYPE_ROLE))
end

function Desktop:_refreshFuncRedPointByRedPointData(keyMap)
    for k , v in pairs(keyMap) do
        self:_refreshFuncRedPoint(k)
    end
end
-- 刷新单个功能id的红点
function Desktop:_refreshFuncRedPoint(funcId)
    local pos = self._model:getFuncRealPos(funcId)
    if pos then
        local btnFunc = self:getBtnByPos(pos)
        if btnFunc then
            local hasRedPoint = false
            if UD.redPoint:hasKey(funcId) then
                hasRedPoint = UD.redPoint:getStateByKey(funcId)
            else
                local badgeNum = UD.badge:getNum(funcId)
                hasRedPoint = badgeNum > 0
            end
            local redPointNode = btnFunc:findChild("Panel/tishi")
            display.setNewPointVisible(redPointNode, hasRedPoint)
        end

        -- 如果是top btn 刷新上部收缩按钮红点
        if self._model:isTopPos(pos) then
            self:_refreshTopSwitchRedPoint()
        end

        -- 如果是btm btn 刷新上部收缩按钮红点
        if (self._openStatus and funcId == Constant.FUNC_TYPE_AVATAR_SHOP) or
            (not self._openStatus and self._model:isBottomPos(pos)) then
            self:_refreshSwitchArrowRedPoint()
        end
    end
end

function Desktop:showRewardRedPoint(funcId, b)
    local pos = self._model:getFuncRealPos(funcId)
    if pos then
        local btnFunc = self:getBtnByPos(pos)
        if btnFunc then
            local redPointNode = btnFunc:findChild("Panel/tishi")
            display.setNewPointVisible(redPointNode, b)
        end
    end
end

-- funcIds 需要刷新红点的功能ids，nil使用所有已开放的功能id
function Desktop:refreshRedPoint(funcIds)
    funcIds = funcIds or self._model:getOpenFuncIds()
    for _,funcId in pairs(funcIds) do
        self:_refreshFuncRedPoint(funcId)
    end

    local totalNewPoint = self.m_bottomNode:findChild("btn_more/tishi")
    if totalNewPoint then
        display.setNewPointVisible(totalNewPoint, self._model:isBottomHaveNew())
    end

    self:_refreshTopSwitchRedPoint()
end

-- 所有按钮的结构都是一致的，统一 01Button 添加事件
-- Node = {
--     Panel = {
--         01Button,
--         tishi
--     }
-- }
function Desktop:_initFuncBtns()
    local btns = {}
    local btn, name, children
    -- top
    children = self.m_topNode:getChildren()
    for _,child in ipairs(children) do
        btns[child:getName()] = child
    end

    -- top left
    local headNode = self._playerRoot
    local btn_50 = headNode:findChild("Panel/Panel_team/button_50")
    local btn_51 = headNode:findChild("Panel/Panel_team/button_51")
    btn_50:setVisible(false)
    btn_51:setPosition(btn_50:getPosition())
    btns["button_50"] = btn_50
    btns["button_51"] = btn_51

    -- top right
    for i=71,74 do
        name = "button_" .. i
        btn = self._miniMap:getFuncBtn(name)
        btns[name] = btn
    end

    -- left
    btns["button_60"] = self._taskRoot:findChild("Panel/button_60")

    -- right
    children = self.m_rightNode:getChildren()
    for _,child in ipairs(children) do
        btns[child:getName()] = child
    end

    -- buttom
    local bottomNode = self.m_bottomNode
    for i=1,16 do
        name = "button_" .. i
        btn = bottomNode:findChild("Panel/Panel_btn/" .. name)
        if not btn then
            btn = bottomNode:findChild("Panel/Panel_other/" .. name)
        end
        if btn then
            btns[name] = btn
        else
            break
        end
    end

    -- setContentSize click
    for k,btn in pairs(btns) do
        local panel = NodeGetChildByName(btn, "Panel")
        btn:setContentSize(panel:getContentSize())
        local button = NodeGetChildByName(panel, "01Button")
        button:addClickEventListener(function(sender)
            local functionId = sender:getTag()
            if functionId == Constant.FUNC_TYPE_MSDK_COMMUNITY then
                self:showMsdkCommunityBtns()
                return
            end
            self:dispatchEvent({name = "onOpenFunction",functionId = functionId})
        end)
    end
    self._funcBtns = btns
end

-- 显示msdk 社区按钮
function Desktop:showMsdkCommunityBtns()
    if not self._msdkCommunityBtns then
        self._msdkCommunityBtns = MsdkCommunityRender.create()
        self.m_topNode:addChild(self._msdkCommunityBtns)
        self._msdkCommunityBtns:addHideFunc(function()
            self._msdkCommunityBtns:setVisible(false)
            self._isShowMsdkCommunity = false
        end)
    end
    if self._isShowMsdkCommunity then
        self._msdkCommunityBtns:setVisible(false)
        self._isShowMsdkCommunity = false
    else
        local funcBnt = self:getBtnByFuncId(Constant.FUNC_TYPE_MSDK_COMMUNITY)
        if funcBnt then
            local posx, posy = funcBnt:getPosition()
            self._msdkCommunityBtns:setVisible(true)
            self._msdkCommunityBtns:setPosition(posx + 45, posy)
            self._isShowMsdkCommunity = true
        end
    end
end

function Desktop:getBtnByPos(pos)
    local buttonName = "button_" .. pos
    return self._funcBtns[buttonName]
end

-- 根据funcId获取btn，因为有未开放的情况
function Desktop:getBtnByFuncId(funcId)
    local pos = self._model:getFuncRealPos(funcId)
    if pos then
        return self:getBtnByPos(pos)
    end
end

--福利的按钮是动态的，图标，功能动态变化，所以不能走通用流程
function Desktop:refreshRewardBtn(params)
    local funcId = params.funcId

    local btnFunc = self:getBtnByFuncId(funcId)
    if btnFunc then
        btnFunc:setVisible(true)

        local btn = btnFunc:findChild("Panel/01Button")

        if params.icon1Path then
            btn:loadTextureNormal(params.icon1Path)
        end

        if params.icon2Path then
            btn:loadTexturePressed(params.icon2Path)
        end
    end
end

function Desktop:_refreshFuncBtn(params)
    local pos = params.atPos or params.pos
    -- local name = params.name
    local funcId = params.funcId
    local iconPath = params.iconPath

    -- 组队查找器，暂时隐藏不用
    if funcId == Constant.FUNC_TYPE_RECRUIT then return end

    local btnFunc = self:getBtnByPos(pos)
    if btnFunc then
        btnFunc:setVisible(true)

        local btn = btnFunc:findChild("Panel/01Button")
        if btn:getTag() ~= funcId then
            btn:setTag(funcId)
            if iconPath then
                if iconPath.icon1Path then
                    btn:loadTextureNormal(iconPath.icon1Path)
                end

                if iconPath.icon2Path then
                    btn:loadTexturePressed(iconPath.icon2Path)
                end
            else
                local icon1Path, icon2Path = GD:getFeatureOnMenuIconPath(funcId)
                if icon1Path then
                    btn:loadTextureNormal(icon1Path,1)
                end
                if icon2Path then
                    btn:loadTexturePressed(icon2Path,1)
                end
            end
        end
    end
end

function Desktop:initFunctionByIds()
    -- hide all func btn
    for _,btn in pairs(self._funcBtns) do
        NodeSetVisibleFunc(btn, false)
    end

    local paramsDict = self._model:getOpenFuncParamsDict()
    for _,params in pairs(paramsDict) do
        self:_refreshFuncBtn(params)
    end

    -- refresh bottom ui
    self.m_bottomMoreBtn:setVisible(self._model:hasBottomFunc())

    -- top btn 1个以上都显示_topSwitch，否则隐藏_topSwitch且打开m_topNode
    local topFuncNum = self._model:getTopFuncNum()
    self._topSwitchVisible = topFuncNum > 0
    if topFuncNum > 0 then
        self._topSwitch:setVisible(true)
        --根据顶部按钮个数设置位置
        local topPanelSize = self.m_topNode:getContentSize().width
        local topPanelPosX = self.m_topNode:getPositionX()
        self._topSwitchLeftPosX = topPanelPosX - topPanelSize + 80*math.max(0, (5 - topFuncNum)) + 4
        if self._isTopOpen then
            self._topSwitch:setPositionX(self._topSwitchLeftPosX)
        end
    else
        self._topSwitch:setVisible(false)
        if not self._isTopOpen then
            self:switchTop(true)
        end
    end
end

------------------------ top btn switch ----------------------
function Desktop:_initTopSwtich()
    self._topSwitchVisible = false
    self._isTopOpen = false
    local topSwitch = self.mUINode:getChildByName("btn_operate")
    self._topSwitch = topSwitch
    self._topSwitchTip = topSwitch:getChildByName("tishi")
    self._topSwitchLeft = topSwitch:getChildByName("btn_p")
    self._topSwitchRight = topSwitch:getChildByName("btn_n")
    self._topSwitchPosY = topSwitch:getPositionY()
    self._topSwitchLeftPosX = topSwitch:getPositionX()
    self._topSwitchRightPosX = self.mUINode:getChildByName("Node_operate"):getPositionX()

    display.uiAddClick(topSwitch, function()
        self:switchTop(true)
    end)

    self:switchTop(false)
end

function Desktop:_refreshTopSwitchRedPoint()
    if self._isTopOpen then
        display.setNewPointVisible(self._topSwitchTip, false)
    else
        local hasNew = self._model:isTopFuncHasNew()
        display.setNewPointVisible(self._topSwitchTip, hasNew)
    end
end

function Desktop:isTopOpen()
    return self._isTopOpen
end

function Desktop:isInTopSwitch()
    return self._isInTopSwitch
end

function Desktop:setTopSwitchOverCB(cb)
    self._topSwitchOverCB = cb
end

function Desktop:switchTop(withAction)
    self._isTopOpen = not self._isTopOpen
    if withAction then
        self._topSwitch:setTouchEnabled(false)
        self._isInTopSwitch = true

        local act
        if self._isTopOpen then
            local moveTo = cca.moveTo(0.2, self._topSwitchLeftPosX, self._topSwitchPosY)
            moveTo = cca.targeted(moveTo, self._topSwitch)
            local scaleTo = cca.scaleTo(0.2, 1)
            act = cca.spawn({moveTo, scaleTo})
        else
            local scaleTo = cca.scaleTo(0.2, 0)
            local moveTo = cca.moveTo(0.2, self._topSwitchRightPosX, self._topSwitchPosY)
            moveTo = cca.targeted(moveTo, self._topSwitch)
            act = cca.spawn({scaleTo, moveTo})
        end
        local cb = cca.callFunc(function()
            self._topSwitchLeft:setVisible(self._isTopOpen)
            self._topSwitchRight:setVisible(not self._isTopOpen)
            self._topSwitch:setTouchEnabled(true)
            self._isInTopSwitch = false
            executeFunc(self._topSwitchOverCB)
        end)

        self.m_topNode:runAction(cca.seq({act, cb}))
    else
        self._topSwitchLeft:setVisible(self._isTopOpen)
        self._topSwitchRight:setVisible(not self._isTopOpen)
        if self._isTopOpen then
            self._topSwitch:setPositionX(self._topSwitchLeftPosX)
            self.m_topNode:setScale(1)
        else
            self._topSwitch:setPositionX(self._topSwitchRightPosX)
            self.m_topNode:setScale(0)
        end
    end

    self:_refreshTopSwitchRedPoint()
end

------------------------ bottom btn action ----------------------
function Desktop:initBottomTimeline()
    self._btmAction = self.m_bottomNode:getTimeline()
    self._btmAction:gotoFrameAndPause(0)
    self._hasOpenAct = self._btmAction:IsAnimationInfoExists("in")
    self._hasCloseAct = self._btmAction:IsAnimationInfoExists("out")
    if self._hasOpenAct then
        local info = self._btmAction:getAnimationInfo("in")
        self._openDuration = info.endIndex - info.startIndex
    end
    if self._hasCloseAct then
        local info = self._btmAction:getAnimationInfo("out")
        self._closeDuration = info.endIndex - info.startIndex
    end
    self.m_bottomMoreBtn:setTouchEnabled(true)
    self.m_bottomMoreBtn:addClickEventListener(function()
        if self._openDelayClick or self._closeDelayClick then return end
        if self._openStatus then
            self:closeBottomAction()
        else
            self:openBottomAction()
        end
    end)
end

-- 下方按钮是否属于打开状态(常用)
function Desktop:isBottomOpen()
    return self._openStatus
end

-- BottomAction 是否在播放中
function Desktop:isBottomActionPlaying()
    return self._openDelayClick or self._closeDelayClick
end

function Desktop:setBottomAcionOverCB(cb)
    self._btmAvtionOverCB = cb
end

function Desktop:_refreshSwitchArrowRedPoint()
    local hasRedPoint = false
    if self._openStatus then
        hasRedPoint = self._model:isBottomSecHaveNew()
    else
        hasRedPoint = self._model:isBottomHaveNew()
    end

    local arrowPointNode = self.m_bottomMoreBtn:getChildByName("tishi")
    display.setNewPointVisible(arrowPointNode, hasRedPoint)
end

function Desktop:_switchArrowStatus()
    local closeImg = self.m_bottomMoreBtn:getChildByName("img_1")
    local openImg = self.m_bottomMoreBtn:getChildByName("img_2")
    if self._openStatus then
        closeImg:setVisible(true)
        openImg:setVisible(false)
    else
        closeImg:setVisible(false)
        openImg:setVisible(true)
    end
end

function Desktop:openBottomAction()
    if not self._openStatus then
        self._openStatus = true
        self._openDelayClick = true
        self._closeDelayClick = false
        self:_switchArrowStatus()
        self.m_bottomBtnPanel:setVisible(true)
        self._btmAction:play("in", false)
        self._btmAction:clearLastFrameCallFunc()
        self:performWithDelay(function()
            self._btmAction:clearLastFrameCallFunc()
            self._openDelayClick = false
            self.m_bottomOtherPanel:setVisible(false)

            self:_refreshSwitchArrowRedPoint()
            executeFunc(self._btmAvtionOverCB)
        end, app:getAnimationInterval() * self._openDuration)
        -- self._btmAction:setLastFrameCallFunc(function()
        --     self._btmAction:clearLastFrameCallFunc()
        --     self._openDelayClick = false
        --     self.m_bottomOtherPanel:setVisible(false)

        --     executeFunc(self._btmAvtionOverCB)
        -- end)

    end
end

function Desktop:closeBottomAction()
    if self._openStatus then
        self._openStatus = false
        self._openDelayClick = false
        self._closeDelayClick = true
        self:_switchArrowStatus()
        self.m_bottomOtherPanel:setVisible(true)
        self._btmAction:play("out", false)
        self._btmAction:clearLastFrameCallFunc()
        -- self._btmAction:setLastFrameCallFunc(function()
        --     self._btmAction:clearLastFrameCallFunc()
        --     self._closeDelayClick = false
        --     self.m_bottomBtnPanel:setVisible(false)

        --     executeFunc(self._btmAvtionOverCB)
        -- end)
        self:performWithDelay(function()
            self._btmAction:clearLastFrameCallFunc()
            self._closeDelayClick = false
            self.m_bottomBtnPanel:setVisible(false)

            self:_refreshSwitchArrowRedPoint()
            executeFunc(self._btmAvtionOverCB)
        end, app:getAnimationInterval() * self._closeDuration)
    end
end


function Desktop:getPlayerInfo()
    return self._playerInfo
end

function Desktop:refreshTeamFlag()
    self._playerInfo:refreshTeamFlag()
end

function Desktop:setLife(percent)
    self._playerInfo:setLifeBar(percent)
end

function Desktop:refreshPlayerInfo(baseInfo)
    self._playerInfo:refreshPlayerInfo(baseInfo)
end

function Desktop:refreshMsdk()
    self._playerInfo:refreshMsdk()
end

function Desktop:refreshTeamGroup()
    self._teamGroup:refreshTeamGroup()
end

function Desktop:getTeamGroup()
    return self._teamGroup
end

function Desktop:getWheel()
    return self._wheel
end

function Desktop:getMiniMap()
    return self._miniMap
end

-- 返回右下角tips Panel
function Desktop:getFourthTips()
    return self._fourthTips
end

function Desktop:getBossNode()
    return self.m_bossNode
end

function Desktop:isRightNodeVisible()
    return self.m_rightNode:isVisible()
end

-- TODO dungeon相关应该移到一个新文件中
function Desktop:showDungeonUi()
    if not self.m_bossNode:isVisible() then
        self.m_rightNode:setVisible(false)
    end

    self._dungeonInfo:showDungeonUi()

    -- 移除英雄之路右下角提示
    self._fourthTips:removeByType(Constant.FUNC_TYPE_TASK_ROADHERO)
end

function Desktop:hideDungeonUi()
    self.m_rightNode:setVisible(true)
    self.m_bossNode:setVisible(false)
    self.m_bossNode:stopAllActions()

    self._dungeonInfo:hideDungeonUi()
end

function Desktop:showDungeonCountDown(second)

    if not self._dountDownScene then
        self._dountDownScene = cc.uiloader:load(Res.DesktopCountDownScene)
        self:addChild(self._dountDownScene,2)
        self._dountDownScene:setContentSize(cc.size(display.width,display.height))
        ccui.Helper:doLayout(self._dountDownScene)

        local uiAction = cc.CSLoader:createTimeline(Res.DesktopCountDownScene)
        self:runAction(uiAction)
        uiAction:gotoFrameAndPlay(0,uiAction:getDuration(),false)
        uiAction:setLastFrameCallFunc(function()

        end)

        local countDownText = self._dountDownScene:findChild("Panel/Text_1")
        local showTime = L("lua_code_text_391")
        countDownText:setString(string.format(showTime,second))

        local startTime = app.session:getServerTime()
        local action = cc.RepeatForever:create(
            cc.Sequence:create(
            cc.DelayTime:create(0.5),
            cc.CallFunc:create(function()
                local TeamModel = app:getInst("TeamModel")
                if not TeamModel:hasTeam() then
                    self:hideDungeonCountDown()
                    return
                end
                local moveTime = app.session:getServerTime() - startTime
                local residueTime = math.floor(second - moveTime)
                residueTime = (residueTime < 0) and 0 or residueTime
                local timeStr = string.format(showTime,residueTime)
                countDownText:setString(timeStr)
                if residueTime <= 0 then
                    DungeonManager:dungeonAway()
                    self:hideDungeonCountDown()
                end
        end)))

        self._dountDownScene:runAction(action)
    end

end

function Desktop:hideDungeonCountDown()
    if self._dountDownScene then
        self:removeChild(self._dountDownScene)
        self._dountDownScene = nil
    end
end

-- 不依赖于副本的倒计时（倒计时结束 或者 切换地图的时候会 自动隐藏）
function Desktop:showNormalCountDown(params)
    if self._normalCountDown then return end

    local second = params.second
    local showTime = params.formatStr
    if not showTime then
        showTime = L("lua_code_text_391")
    end

    self._normalCountDown = cc.CSLoader:createNode(Res.DesktopCountDownScene, true)
    self:addChild(self._normalCountDown, 2)
    self._normalCountDown:setContentSize(cc.size(display.width, display.height))
    ccui.Helper:doLayout(self._normalCountDown)
    self._normalCountDown:getTimeline():gotoFrameAndPlay(0, false)

    local endTime = app.session:getServerTime() + second
    local countDownText = self._normalCountDown:findChild("Panel/Text_1")

    local function _tick(dt)
        local curTime = app.session:getServerTime()
        local remainedTime = math.ceil(endTime - curTime)
        countDownText:setString(string.format(showTime, remainedTime))
       
        if remainedTime <= 0 then
            self:hideNormalCountDown()
        end
    end

    self._normalCountDownIdx = scheduler.newCron(_tick, 0.5, true)
    _tick()
end

function Desktop:hideNormalCountDown()
    if self._normalCountDown then
        self:removeChild(self._normalCountDown)
        self._normalCountDown = nil
    end
    if self._normalCountDownIdx then
        scheduler.cancelCron(self._normalCountDownIdx)
        self._normalCountDownIdx = nil    
    end
end

-------------------------->>>>>>>> 以下：狮心号角 桌面处理 <<<<<<<<--------------------------
function Desktop:hideLionHornDesktop()
    self.m_rightNode:setVisible(false)
    self._wheel:getUIRoot():setVisible(false)

    self.mUINode:getChildByName("task"):setVisible(false)
    self._taskRoot:setVisible(false)

    -- app:getLaunchCtl():disableTouchLayer()
    FieldManager:stopTouch(true)
end

-------------------------->>>>>>>> 以下：冠军赛准备场 桌面处理 <<<<<<<<--------------------------
function Desktop:hideChampionDesktop()
    self.m_rightNode:setVisible(false)

    self.mUINode:getChildByName("task"):setVisible(false)
    self._taskRoot:setVisible(false)
end

-------------------------->>>>>>>> 以下：跨服 工会战准备场 桌面处理 <<<<<<<<--------------------------
function Desktop:hideCSGuildWarDesktop()

    self.m_bottomNode:setVisible(true)
    self._topSwitch:setVisible(false)
    self.m_topNode:setVisible(false)
    self._taskRoot:setVisible(false)
    self.m_rightNode:setVisible(false)
    
    local teamGroupRoot = self._playerRoot:findChild("Panel/Panel_head")
    local teamFunctionRoot = self._playerRoot:findChild("Panel/Panel_team")
    teamGroupRoot:setVisible(true)
    teamFunctionRoot:setVisible(true)
    self._miniMap:hideBtns()
end

function Desktop:hideCSGuildWarDesktopState2()
    self.m_bottomNode:setVisible(false)
    self._topSwitch:setVisible(false)
    self.m_topNode:setVisible(false)
    self._taskRoot:setVisible(false)
    self.m_rightNode:setVisible(false)

    local teamGroupRoot = self._playerRoot:findChild("Panel/Panel_head")
    local teamFunctionRoot = self._playerRoot:findChild("Panel/Panel_team")
    teamGroupRoot:setVisible(false)
    teamFunctionRoot:setVisible(false)

    self._miniMap:hideBtns()
end


-------------------------->>>>>>>> 以下：公会战准备场 桌面处理 <<<<<<<<--------------------------
function Desktop:hideDynastyDesktop()
    self.m_rightNode:setVisible(false)
    self.m_topNode:setVisible(false)
    self._topSwitch:setVisible(false)

    self.mUINode:getChildByName("task"):setVisible(false)
    self._taskRoot:setVisible(false)
end


function Desktop:resetDesktop()
    self.m_rightNode:setVisible(true)
    self.m_topNode:setVisible(true)
    self._topSwitch:setVisible(self._topSwitchVisible)
    self._wheel:getUIRoot():setVisible(true)

    self.mUINode:getChildByName("task"):setVisible(true)
    self._taskRoot:setVisible(true)

    local teamGroupRoot = self._playerRoot:findChild("Panel/Panel_head")
    local teamFunctionRoot = self._playerRoot:findChild("Panel/Panel_team")
    teamGroupRoot:setVisible(true)
    teamFunctionRoot:setVisible(true)

    self._miniMap:resetBtns()

    app:getLaunchCtl():resetTouchLayerEnable()
end

-- 处理功能预览icon
function Desktop:setGamePlayPreviewIcon( iconPath )
    if iconPath and "" ~= iconPath then
        local btnNode = self:getBtnByFuncId( Constant.FUNC_TYPE_PREVIEW )
        if btnNode then
            local btn = btnNode:findChild( "Panel/01Button" )
            if btn then
                btn:loadTextureNormal(iconPath)
                btn:loadTexturePressed(iconPath)
            end
        end
    end
end

function Desktop:refreshMsdkHead()
    self._playerInfo:refreshHead()
end

function Desktop:isShowSkillChangeNode(b)
    if not self.m_skillChangeNode then return end
    self.m_skillChangeNode:setVisible(b)
end

-------------------------->>>>>>>> 以下：广告弹窗节点 <<<<<<<<--------------------------
function Desktop:createAdvertNode(data)
    if not self._advertNode then
        local advertNode = self.mUINode:getChildByName("advert")
        self._advertNode = Advert.create()
        self.mUINode:addChild(self._advertNode)
        self._advertNode:setPosition(advertNode:getPosition())
        self._advertNode:setVisible(false)
    end
    if data then
        self._advertNode:setData(data)
        self._advertNode:setVisible(true)
    end
end

function Desktop:removeAdvertNode()
    if self._advertNode then
        self.mUINode:removeChild(self._advertNode)
        self._advertNode = nil
    end
end

function Desktop:getAdvertNode()
    return self._advertNode
end


function Desktop:refreshSecretInfo()
    if self._secretInfo then
        self._secretInfo:refreshUI()
    end
end
    

return Desktop
